import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/entity/user_info_entity.dart';
import 'package:taonile/provider/userinfo_provider.dart';
import 'package:taonile/utils/user_utils.dart';
import 'package:taonile/views/default_views.dart';
import 'package:taonile/views/dialog_manager.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../entity/my_collect_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';

class MineCollectMallPage extends StatefulWidget {
  MineCollectMallPage({Key? key}) : super(key: key);

  @override
  State<MineCollectMallPage> createState() => _MineCollectMallPageState();
}

class _MineCollectMallPageState extends State<MineCollectMallPage> {
  late List<MyCollectDataData> datas = [];
  var page = 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getDatas();
  }

  getDatas() async {
    dynamic result =
        await Api.collectionList({'page': page.toString(), 'limit': '20', 'type': 'shop'});
    MyCollectEntity entity = MyCollectEntity.fromJson(result);
    setState(() {
      if (page == 1) {
        datas.clear();
      }
      if (entity.data.data.isNotEmpty) {
        page++;
        datas.addAll(entity.data.data);
      }
    });
  }

  collection(String storeId) async {
    dynamic result = await Api.collection({'id': storeId, 'type': 'shop'});
    setState(() {
      var jsonResult = jsonDecode(jsonEncode(result));
      if (jsonResult['code'] == 1) {
        EasyLoading.showToast(jsonResult['msg']);
        page = 1;
        getDatas();
      }
    });
  }

  Widget getProductItem(int index) {
    return Container(
      height: 140.w,
      decoration:
          BoxDecoration(color: Config.colorWhite, borderRadius: BorderRadius.circular(12.w)),
      margin: EdgeInsets.symmetric(horizontal: 25.w, vertical: 11.w),
      child: InkWell(
        onTap: () {
          Routes.navigateTo(context, Routes.mallHome, params: {'storeId': datas[index].id});
        },
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              margin: EdgeInsets.only(left: 20.w, right: 20.w),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(5),
                child: CachedNetworkImage(
                  imageUrl: datas[index].logo,
                  fit: BoxFit.fill,
                  width: 100.w,
                  height: 100.w,
                  errorWidget: (context, url, error) {
                    return Image.asset(
                      'assets/images/bg_default_400.png',
                      width: 100.w,
                      height: 100.w,
                      fit: BoxFit.fill,
                    );
                  },
                ),
              ),
            ),
            Container(
              height: 110.w,
              width: 400.w,
              child: Stack(
                children: [
                  Text(
                    datas[index].title,
                    softWrap: true,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: (Config.colorText1), fontSize: 22.w),
                  ),
                  Positioned(
                    bottom: 5.w,
                    child: Text(
                      "${datas[index].saveNum}人收藏",
                      softWrap: true,
                      style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 0.w),
              width: 140.w,
              height: 46.w,
              child: ElevatedButton(
                clipBehavior: Clip.antiAlias,
                onPressed: () {
                  collection(datas[index].id);
                },
                style: ButtonStyle(
                  elevation: MaterialStateProperty.all(0),
                  backgroundColor: MaterialStateProperty.all(Colors.white),
                  shape: MaterialStateProperty.all(
                    RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(24.w),
                    ),
                  ),
                  side: MaterialStateProperty.all(
                    BorderSide(color: Config.colorText3, width: 2.w),
                  ),
                ),
                child: Text(
                  '取消收藏',
                  style: TextStyle(fontSize: 18.sp, color: Config.colorText3),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 1270.w,
      child: datas.isNotEmpty
          ? EasyRefresh(
              header: const MaterialHeader(),
              footer: const MaterialFooter(),
              onRefresh: () async {
                await Future.delayed(const Duration(milliseconds: 200), () {
                  page = 1;
                  getDatas();
                });
              },
              onLoad: () async {
                getDatas();
              },
              child: ListView.builder(
                // shrinkWrap: true,
                // scrollDirection: Axis.vertical,
                // physics: const BouncingScrollPhysics(),
                padding: EdgeInsets.symmetric(vertical: 5.w),
                itemCount: datas.length,
                itemBuilder: (BuildContext context, int index) {
                  return getProductItem(index);
                },
              ),
            )
          : showNullData(),
    );
  }
}
